package org.opensuse.bs.ui.actions;

import java.util.Vector;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.opensuse.bs.ui.OSC;
import org.opensuse.bs.ui.model.BSModelElement;
import org.opensuse.bs.ui.model.RemotePackage;
import org.opensuse.bs.ui.model.RemoteProject;

public class RemoveRemote implements IObjectActionDelegate {
	private ITreeSelection selected;
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}
	
	public void run(IAction action) {
		if(selected == null)return;
		if(!MessageDialog.openQuestion(
				null, 
				"Delete action dialog", 
				"Are you really sure?")
				)return;
		TreePath path = selected.getPaths()[0];
		Object o = path.getLastSegment();
		if(o instanceof RemoteProject) {
			final String prj = ((BSModelElement) o).getName();
			Job job = new Job("Deleting project "+prj) {
				protected IStatus run(IProgressMonitor monitor) {
					Vector<String> result = OSC.run("deleteprj -f "+prj);
					if(result.isEmpty()) {
						return Status.CANCEL_STATUS;
					}
					return Status.OK_STATUS;
				}
			};
			job.schedule();
		}else if(o instanceof RemotePackage) {
			final String pkg = ((BSModelElement) o).getName();
			final String prj = ((BSModelElement) path.getFirstSegment()).getName();
			Job job = new Job("Deleting package "+pkg) {
				protected IStatus run(IProgressMonitor monitor) {
					Vector<String> result = OSC.run("deletepac "+prj+" "+pkg);
					if(result.isEmpty()) {
						return Status.CANCEL_STATUS;
					}
					return Status.OK_STATUS;
				}
			};
			job.schedule();
		}
	}
	
	public void selectionChanged(IAction action, ISelection selection) {
		if(selection instanceof ITreeSelection) {
			selected = (ITreeSelection) selection;
		}
 	}

}
